package com.tenqian.handler;

import com.alibaba.fastjson.JSONObject;
import com.tenqian.enums.ResultEnum;
import com.tenqian.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginHandler extends HandlerInterceptorAdapter {
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置编码
        response.setHeader("Content-Type", "text/json;charset=UTF-8");
        String tokenKey = request.getParameter("token");
        //没有token参数或者token参数为空
        if (StringUtils.isBlank(tokenKey)) {
            unlogin(response);
            return false;
        }
        String s = redisTemplate.opsForValue().get("token:" + tokenKey);
        //如果token存在,放行
        if (StringUtils.isNotBlank(s)) {
            return true;
        }
        unlogin(response);
        //如果不存在则拦截
        return false;
    }

    private void unlogin(HttpServletResponse response) throws IOException {
        response.getWriter().print(JSONObject.toJSONString(ResultUtil.error(ResultEnum.UNLOGIN_ERROR)));
    }

}
